//
//  AppDelegate.m
//  YaoHeAPP
//
//  Created by mac on 15/11/20.
//  Copyright (c) 2015年 mac. All rights reserved.
//

#import "AppDelegate.h"
#import "ExceptionHandler.h"
#import "Controller.h"

#import "YunBaService.h"
#import "JKNotifier.h"
#import "RootTabBarViewController.h"
#import "Tool.h"
#import "JSONKit.h"
#import "pushDatamodel.h"

#import "LoginVC.h"
#import "Define.h"

#import <ShareSDK/ShareSDK.h>
#import <ShareSDKConnector/ShareSDKConnector.h>
//微信SDK头文件
#import "WXApi.h"
//腾讯开放平台（对应QQ和QQ空间）SDK头文件
#import <TencentOpenAPI/TencentOAuth.h>
#import <TencentOpenAPI/QQApiInterface.h>
#import "UMMobClick/MobClick.h"



@interface AppDelegate ()
{
    NSString *trackViewURL;

}

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window.backgroundColor=bgVCcolor;
     [UIApplication sharedApplication].statusBarStyle=UIStatusBarStyleLightContent;
    //崩溃信息处理
    ExceptionHandlers

    NSString *documents = [NSHomeDirectory()stringByAppendingPathComponent:@"Documents"];
    NSString *path = [documents stringByAppendingPathComponent:@"IOS_exceptionHandler.txt"];
    NSFileManager*fileManager=[NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:path]==YES)
    {
        [Controller upIOSExceptionHandler];
    }
    
    kYBLogLevel = kYBLogLevelDebug;
    [self  registerRemoteNotification];

    //公司测试  55f3e6b63e992c0c42dd3f7f
    //公网 5620637dbe17bc415cfbf0b5
    [YunBaService setupWithAppkey:@"5620637dbe17bc415cfbf0b5"];
    
    /**
     *  topic
     *
     *  @param succ  subscribe: topic（频道） 字符串 列如你接受123频道 然后发送推送
     *  @param error 接受失败的情况
     *
     *  @return 失败原因
     */
    [YunBaService subscribe:@"all" resultBlock:^(BOOL succ, NSError *error){
        if (succ) {
        }
    }];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onMessageReceived:) name:kYBDidReceiveMessageNotification object:nil];
    
    NSDictionary *apnOption = [launchOptions objectForKey: UIApplicationLaunchOptionsRemoteNotificationKey];
    if (apnOption) {
        //推送返回数据自己看着处理:------%@",apnOption
    }

    [self saveCityAndSheng];
    
    //share分享注册
    /**
     *  设置ShareSDK的appKey，如果尚未在ShareSDK官网注册过App，请移步到http://mob.com/login 登录后台进行应用注册，
     *  在将生成的AppKey传入到此方法中。
     *  方法中的第二个第三个参数为需要连接社交平台SDK时触发，
     *  在此事件中写入连接代码。第四个参数则为配置本地社交平台时触发，根据返回的平台类型来配置平台信息。
     *  如果您使用的时服务端托管平台信息时，第二、四项参数可以传入nil，第三项参数则根据服务端托管平台来决定要连接的社交SDK。
     */
    [ShareSDK registerApp:@"dec69ab109a6"activePlatforms:@[@(SSDKPlatformTypeWechat),@(SSDKPlatformTypeQQ)]
                 onImport:^(SSDKPlatformType platformType)
     {
         switch (platformType)
         {
             case SSDKPlatformTypeWechat:
                 [ShareSDKConnector connectWeChat:[WXApi class]];
                 break;
             case SSDKPlatformTypeQQ:
                 [ShareSDKConnector connectQQ:[QQApiInterface class] tencentOAuthClass:[TencentOAuth class]];
                 break;
             default:
                 break;
         }
     }
          onConfiguration:^(SSDKPlatformType platformType, NSMutableDictionary *appInfo)
     {
         
         switch (platformType)
         {
             case SSDKPlatformTypeWechat:
                 [appInfo SSDKSetupWeChatByAppId:@"wx92c9181f6fb2136f"
                                       appSecret:@"5d317108fdfe70dd81282bedb1c8720a"];
                 break;
             case SSDKPlatformTypeQQ:
                 [appInfo SSDKSetupQQByAppId:@"1104911700"
                                      appKey:@"sRlPnsxheBcsQeFH"
                                    authType:SSDKAuthTypeBoth];
                 break;
             default:
                 break;
         }
     }];
    
    //  友盟的方法本身是异步执行，所以不需要再异步调用
    [self umengTrack];
    
    [self.window makeKeyAndVisible];

    return YES;

}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
}

- (void)onMessageReceived:(NSNotification *)notification {
    
    YBMessage *message = [notification object];
    
    NSString *payloadString = [[NSString alloc] initWithData:[message data] encoding:NSUTF8StringEncoding];
    
    NSDictionary *pushdata=[pushDatamodel dictionaryWithJsonString:payloadString];
    
    //下面是不在列表页
    //1.1取出里面的userid
    
    NSString *usid=[NSString  stringWithFormat:@"%@",[[NSUserDefaults standardUserDefaults] objectForKey:USERID]] ;
    NSString *uu;
    BOOL useris=YES;
     pushDatamodel *pushmodel=[[pushDatamodel alloc]initWith:pushdata];
    if ([pushmodel.To isKindOfClass:[NSNull class]]||pushmodel.To==nil||pushmodel.To==NULL||pushmodel.To.count==0 ) {
        useris=YES;
    }else{
        for (NSInteger i=0; i<pushmodel.To.count; i++) {
         uu=[NSString  stringWithFormat:@"%@", pushmodel.To[i]];
        if ([uu isEqualToString:usid]) {
            useris=YES;
        }else{
        
            useris=NO;
        }
    }
    }
    //1.先判断publish是否相等如果相等不发通知
    NSString * publiser = [[NSUserDefaults standardUserDefaults] objectForKey:PUBLISHER];
    BOOL Okpub=YES;
//    NSString *pushing=pushmodel.publisher;
    if([pushmodel.publisher isEqual:[NSNull null]])
    {
         Okpub=YES;
        
    }else if(pushmodel.publisher.length!=0&&[pushmodel.publisher isEqualToString:publiser]){
        Okpub=NO;
    
    }else{
    
        Okpub=YES;
    }
    
    
    
    if (Okpub&&pushmodel.receivertype==1&&useris) {
        //通过这些调节过滤 证明可以发送消息
//        //判断在不在列表页
//        NSString  *VALUE =[[NSUserDefaults standardUserDefaults]  objectForKey:@"SHOPCAR_SHOW_NOW"];
//        //不在列表页 VALUE==nil
//        if (VALUE==nil) {
//            //不在列表页
//        }else{
//            //在列表页
//            
//            
//            
//        }
        
        //当前是列表页的时候可以直接相应通知
        [[NSNotificationCenter defaultCenter] postNotificationName:@"upview" object:pushdata];
        
        //上面的只有正在列表才实现
        NSString *notiftion=pushdata[@"Notification"];
        
        
        if ([notiftion isKindOfClass:[NSNull class]]) {
            
            return;
           
        }else{
            JKNotifierBar *bar =  [JKNotifier showNotiferRemain:[NSString stringWithFormat:notiftion,[self random]]];
        
            [bar handleClickAction:^(NSString *name,NSString *detail,JKNotifier *notifer) {
                [notifer dismiss];
                RootTabBarViewController *rootTabBarViewController = [RootTabBarViewController rootViewController];
                [rootTabBarViewController changeRootViewControllerTo:1];
            }];

        }
    
    }
}

-(NSString*)random{
    
    NSInteger count = 8;
    char chars[] = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLOMNOPQRSTUVWXYZ";
    char codes[count];
    
    for(int i=0;i<count; i++){
        codes[i]= chars[arc4random()%62];
    }
    
    NSString *text = [[NSString alloc] initWithBytes:codes
                                              length:count encoding:NSUTF8StringEncoding];
    return text;
}

-(void)saveCityAndSheng
{
    
    [Controller requestWithURL:@"AppUserCenter/PostAppArea?from=app" jsondic:nil finishBlock:^(ClassData *classData) {
        if ([classData.number integerValue]==0) {
            NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
            NSDictionary*dic=classData.data;
            if ([[dic allKeys] containsObject:@"CITY_NAME"]) {
                NSString*NcityName=[NSString stringWithFormat:@"%@",dic[@"CITY_NAME"]];
                if ([NcityName isEqual:@"<null>"]) {
                    return ;
                }
                else{
                    [userDefaults setObject:NcityName forKey:@"NcityName"];
                }
            }
            if ([[dic allKeys] containsObject:@"PROVINCE_NAME"]) {
                NSString*NshengName=[NSString stringWithFormat:@"%@",dic[@"PROVINCE_NAME"]];
                if ([NshengName isEqual:@"<null>"]) {
                    return ;
                }
                else{
                    [userDefaults setObject:NshengName forKey:@"NshengName"];

                }
            }
        }
        
        
    }];
    
}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}


#pragma mark - 进入前后台都将徽标清零
- (void)applicationDidEnterBackground:(UIApplication *)application {
    [application setApplicationIconBadgeNumber:0];
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    if (application.applicationIconBadgeNumber ) {
        
    }
    [application setApplicationIconBadgeNumber:0];

}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    if (application.applicationIconBadgeNumber >0) {
        //badge number 不为0，说明程序有那个圈圈图标
        //这里进行有关处理
        //        [application setApplicationIconBadgeNumber:0];   //将图标清零。
    }
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


#pragma mark - apns & device token
- (void)registerRemoteNotification {
    //注册APNs，申请获取device token
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
    {
        [[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings
                                                                             settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]];
        [[UIApplication sharedApplication] registerForRemoteNotifications];
    }
    else
    {
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];
    }
}

- (void)unregisterRemoteNotification {
    [[UIApplication sharedApplication] unregisterForRemoteNotifications];
}

// for device token
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
        [YunBaService storeDeviceToken:deviceToken resultBlock:^(BOOL succ, NSError *error) {
        if (succ) {
            
        }
    }];
    
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *) error {
    
    if ([[[UIDevice currentDevice] model] rangeOfString:@"Simulator"].location != NSNotFound)
    { }

    
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    
}

- (void)clearBadgeAndNotifications {
    if ([UIApplication sharedApplication].applicationIconBadgeNumber) {
        [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    } else {
        
        [[UIApplication sharedApplication] setApplicationIconBadgeNumber:1];
        [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    }
}

- (void)umengTrack {
//    [MobClick setAppVersion:XcodeAppVersion]; //参数为NSString * 类型,自定义app版本信息，如果不设置，默认从CFBundleVersion里取
    [MobClick setLogEnabled:NO];
    UMConfigInstance.appKey = @"5743ec37e0f55aa5c2001ac6";
    UMConfigInstance.channelId = @"App Store";
    
    NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    [MobClick setAppVersion:version];
    [MobClick startWithConfigure:UMConfigInstance];
    
//    Class cls = NSClassFromString(@"UMANUtil");
//    SEL deviceIDSelector = @selector(openUDIDString);
//    NSString *deviceID = nil;
//    if(cls && [cls respondsToSelector:deviceIDSelector]){
//        deviceID = [cls performSelector:deviceIDSelector];
//    }
//    NSData* jsonData = [NSJSONSerialization dataWithJSONObject:@{@"oid" : deviceID}
//                                                       options:NSJSONWritingPrettyPrinted
//                                                         error:nil];
//    
}

@end
